<template>
  <a-modal
    :title="data.id && '编辑考勤设置'||'新增考勤设置'"
    centered
    :visible="true"
    width="700"
    @cancel="dialogClosed"
  >

    <a-form
      :form="form"
    >
      <a-row style="width:700px">
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="部门" class="label-width-auto" v-bind="formItemLayout">
            <a-select
              v-decorator="[ 'departmentId', {
                rules: [{ required: true, message: '请选择一个部门' }]
              }]"
              placeholder="请选择"
              @change="handleChange"
            >
              <a-select-option
                v-for="item in departmentList"
                :key="item.deptId"
                :value="item.deptId"
              >
                {{ item.deptName }}
              </a-select-option>

            </a-select>

          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="员工" class="label-width-auto" v-bind="formItemLayout">
            <a-select
              v-decorator="[ 'selectedStaffs', {
                rules: [{ required: true, message: '请选择员工' }]
              }]"
              mode="multiple"
              placeholder="请选择"
              @change="handleSelect"
            >
              <a-select-option
                v-for="item in staffList"
                :key="item.userId"
                :value="item.userId"
              >
                {{ item.name }}
              </a-select-option>

            </a-select>

          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="类型" class="label-width-auto" v-bind="formItemLayout">
            <a-radio-group
              v-decorator="['type', {
                rules: [{ required: true, message: '请选择类型' }],
                initialValue: '普通考勤'
              }]"
            >
              <a-radio-button value="普通考勤">普通考勤</a-radio-button>
              <a-radio-button value="多班轮换">多班轮换</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="班次" class="label-width-auto" v-bind="formItemLayout">
            <a-select
              v-decorator="[ 'selectedPlan', {
                rules: [{ required: true, message: '请选择一个班次' }]
              }]"
              :mode="dataForm.type==='普通考勤'?'default':'multiple'"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in planList"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>

            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <div v-if="dataForm.type==='多班轮换'">
        <a-row>
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item extra="如果周期为1天，那么打完一天卡后，第二天两组打卡时间交换" label="换班周期" class="label-width-auto" v-bind="formItemLayout">
              <a-input-number
                v-decorator="[
                  'cycle',
                  { rules: [{ required: true, message: '请输入换班周期' }] },
                ]"
                :min="1"
                placeholder="请输入"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item label="换班重置" class="label-width-auto" v-bind="formItemLayout">
              <a-radio-group
                v-decorator="['cycleResetType', {
                  rules: [{ required: true, message: '请选择重置方式' }],
                  initialValue: '每周重置'
                }]"
              >
                <a-radio-button value="每周重置">每周重置</a-radio-button>
                <a-radio-button value="每月重置">每月重置</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-for="(planId, index) in selectedPlan" :key="index">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :label="'第' + (index+1) + '组'" class="label-width-auto" v-bind="formItemLayout">
              <a-select
                v-decorator="[ `selectedTeacher4Group[${index}]`, {
                  rules: [{ required: true, message: '请选择至少一个老师' }]
                }]"
                mode="multiple"
                placeholder="请选择"
                :filter-option="handleSelectFilter"
              >
                <a-select-option
                  v-for="item in selectedStaffs"
                  :key="item.userId"
                  :value="item.userId"
                >
                  {{ item.name }}
                </a-select-option>

              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <a-row>
        <a-col :lg="24" :md="24" :sm="24">
          <a-form-item label="迟到或早退" class="label-width-auto" v-bind="formItemLayout">
            <a-row v-for="(point, index) in pointList" :key="index" type="flex" justify="space-around" align="middle">
              <a-col :lg="11" :md="11" :sm="22">
                <a-form-item label="分钟内" v-bind="formItemLayout">
                  <a-input-number
                    v-decorator="[
                      `points[${index}].earlyOrLateMin`,
                      { initialValue:point.earlyOrLateMin},
                    ]"
                    :min="1"
                    placeholder="请输入"
                  />
                </a-form-item>

              </a-col>
              <a-col :lg="11" :md="11" :sm="22">
                <a-form-item label="扣分" v-bind="formItemLayout">
                  <a-input-number
                    v-decorator="[
                      `points[${index}].reducingPoint`,
                      { initialValue:point.reducingPoint},
                    ]"
                    :min="1"
                    placeholder="请输入"
                  />
                </a-form-item>
              </a-col>
              <a-col :lg="2" :md="2" :sm="2">
                <a-form-item class="label-width-auto" v-bind="formItemLayout">
                  <a-icon v-if="index === 0" type="plus-circle" style="cursor:pointer" @click="handleAdd()" />
                  <a-icon v-if="index !== 0" type="minus-circle" style="cursor:pointer" @click="handleDel(index)" />
                </a-form-item>
              </a-col>

            </a-row>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <span slot="footer" class="dialog-footer">
      <a-button @click="dialogClosed()">取消</a-button>
      <a-button id="submit" :loading="submitButton.status" type="primary" @click="dataFormSubmit()">{{ submitButton.text }}</a-button>
    </span>
  </a-modal>
</template>
<style lang="less" scoped>
  .ant-form-item{
    margin-bottom: 5px;
  }
</style>

<script>
import { edit, get, getStaff, getPlan } from '@/pages/attendance/api/attendanceSchedule'
import formItem from '@/config/formItemLayout'
export default {
  name: 'AttendanceScheduleSave',
  props: {
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      form: this.$form.createForm(this, { onValuesChange: this.onValuesChange }),
      formItemLayout: formItem,
      dataForm: {
        id: null,
        type: '普通考勤'
      },
      departmentList: [],
      staffList: [],
      planList: [],
      pointList: [{ earlyOrLateMin: null, reducingPoint: null }],
      selectedPlan: [],
      selectedStaffs: [],
      submitButton: {
        text: '提交',
        status: false
      }
    }
  },
  mounted () {
    this.$departmentListFunc().then(data => {
      this.departmentList = data
    })
    this.$ajaxSend(getPlan, {}, {
      success: datas => { this.planList = datas.records }
    })
    if (this.data.id) {
      this.$ajaxSend(get, this.data.id, {
        success: (data) => {
          data.selectedStaffs = data.teachers.map(teacher => teacher.staffId)
          data.selectedStaffs = [...new Set(data.selectedStaffs)]
          if (data.type === '普通考勤') {
            data.selectedPlan = data.plans[0].id
          } else {
            data.selectedPlan = data.plans.map(plan => plan.id)
            data.selectedTeacher4Group = []
            data.teachers.forEach((teacher) => {
              if (!data.selectedTeacher4Group[teacher.groupIndex]) {
                data.selectedTeacher4Group[teacher.groupIndex] = []
              }
              data.selectedTeacher4Group[teacher.groupIndex].push(teacher.staffId)
            })
          }
          this.pointList = data.points
          this.dataForm = data
          this.$initForm(this.form, this.dataForm)
          this.$ajaxSend(getStaff(this.dataForm.id || -1), { deptId: data.departmentId, page: -1 }, {
            success: datas => {
              this.staffList = datas.records.filter(data => data.userId)
              this.$initForm(this.form, this.dataForm)
            }
          })
        }
      })
    }
  },
  methods: {
    dialogClosed () {
      this.$emit('dialogClosed')
    },
    // 表单提交
    dataFormSubmit () {
      this.$saveQuit('form', edit(this.data.id), (data) => {
        data.id = this.data.id || null

        if (data.type === '普通考勤') {
          data.plans = [{ planId: this.selectedPlan }]
          data.teachers = data.selectedStaffs.map(staffId => { return { staffId: staffId } })
        } else {
          data.teachers = []
          data.selectedTeacher4Group.forEach((arr, index) => {
            arr.forEach(userId => {
              data.teachers.push(
                { staffId: userId, groupIndex: index })
            })
          })
        }

        data.attach = null
        return data
      })
    },
    initStaffList (deptId) {
      this.$ajaxSend(getStaff(this.dataForm.id || -1), { deptId: deptId, pageSize: -1 }, {
        success: datas => { this.staffList = datas.records.filter(data => data.userId) }
      })
    },
    handleChange (value) {
      this.form.setFieldsValue({ selectedStaffs: [] })
      this.initStaffList(value)
    },
    handleSelect (selectedStaffs) {
      // this.staffList.forEach(staff => {
      //   if (selectedStaffs.includes(staff.userId)) {
      //     staff.isSelected = true
      //   }
      // })
      // this.staffList = this.staffList.slice()
    },
    handleAdd () {
      this.pointList.push({ earlyOrLateMin: null, reducingPoint: null })
    },
    handleDel (index) {
      this.pointList.splice(index, 1)
    },
    onValuesChange (props, value) {
      console.log('value', value)
      console.log('value.selectedPlan', value.selectedPlan)
      if (!value.departmentId && value.type) {
        this.dataForm.type = value.type
        if (value.type === '普通考勤') {
          this.form.setFieldsValue({ selectedPlan: null })
        } else {
          this.form.setFieldsValue({ selectedPlan: [] })
        }
      }
      if (value.selectedPlan) {
        if (value.type === '普通考勤') {
          this.selectedPlan = [value.selectedPlan]
        } else {
          this.selectedPlan = value.selectedPlan
        }
      }
      if (value.selectedStaffs) {
        this.selectedStaffs = this.staffList.filter(staff => value.selectedStaffs.includes(staff.userId))
      }
    },
    handleSelectFilter (v, o) {
      return (
        o.componentOptions.children[0].text.toLowerCase().indexOf(v.toLowerCase()) >= 0
      )
    }
  }
}
</script>
